package com.wenbing.miio.core;

import com.wenbing.miio.core.exception.MacFormatException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * mac地址类
 * @author wen bing
 * @projectName: miio
 * @package: com.wenbing.miio
 * @className: MacAddress
 * @date 2024/09/19 15:52
 **/
public final class MacAddress {
    public static final int MAC_LENGTH = 6;
    private byte[] address;

    private MacAddress(byte[] address) {
        assert address != null && address.length == MAC_LENGTH;
        this.address = address;
    }

    public byte[] toBytes() {
        return this.address;
    }

    public static boolean isMacAddress(String mac) {
        Pattern pattern = Pattern.compile("^([A-Fa-f0-9]{2}[-,:]){5}[A-Fa-f0-9]{2}$");
        Matcher matcher = pattern.matcher(mac);
        return matcher.matches();
    }

    public static MacAddress parse(String oui, String nic) {
        return parse(oui + ":" + nic);
    }

    public static MacAddress parse(String str) {
        if (!isMacAddress(str)) {
            throw new MacFormatException();
        }
        String[] address = str.split("[-,:]");
        byte[] mac = new byte[MAC_LENGTH];
        for (int i = 0; i < MAC_LENGTH; i++) {
            mac[i] = Byte.parseByte(address[i], 16);
        }
        return new MacAddress(mac);
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        for (byte i : address) {
            //字节转换为整数
            String str = Integer.toHexString(i & 0xff);
            if (str.length() == 1) {
                builder.append('0');
            }
            builder.append(str);
            builder.append(':');
        }
        return builder.substring(0, builder.length() - 1);
    }
}
